#! /usr/bin/env bash 
# texi2dvi --- produce DVI (or PDF) files from Texinfo (or (La)TeX) sources.
# $Id: texi2dvi,v 1.65 2005/10/24 00:33:43 karl Exp $
#
# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2001,
# 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, you can either send email to this
# program's maintainer or write to: The Free Software Foundation,
# Inc.; 51 Franklin Street, Fifth Floor; Boston, MA 02110-1301, USA.
#
# Original author: Noah Friedman.
#
# Please send bug reports, etc. to bug-texinfo@gnu.org.
# If possible, please send a copy of the output of the script called with
# the `--debug' option when making a bug report.

test -f /bin/ksh && test -z "$RUNNING_KSH" \
  && { UNAMES=`uname -s`; test "x$UNAMES" = xULTRIX; } 2>/dev/null \
  && { RUNNING_KSH=true; export RUNNING_KSH; exec /bin/ksh $0 ${1+"$@"}; }
unset RUNNING_KSH

# This string is expanded by rcs automatically when this file is checked out.
rcs_revision='$Revision: 1.65 $'
rcs_version=`set - $rcs_revision; echo $2`
program=`echo $0 | sed -e 's!.*/!!'`
version="texi2dvi (GNU Texinfo 4.8) $rcs_version

Copyright (C) 2005 Free Software Foundation, Inc.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.  You may redistribute copies of GNU texinfo
under the terms of the GNU General Public License.
For more information about these matters, see the file named COPYING.
"

build_mode=${TEXI2DVI_BUILD_MODE:-local}
build_dir=${TEXI2DVI_BUILD_DIRECTORY:-.}

usage="Usage: $program [OPTION]... FILE...

Run each Texinfo or (La)TeX FILE through TeX in turn until all
cross-references are resolved, building all indices.  The directory
containing each FILE is searched for included files.  The suffix of FILE
is used to determine its language ((La)TeX or Texinfo).  To process
(e)plain TeX files, set the environment variable LATEX=tex.

In order to make texi2dvi a drop-in replacement of TeX/LaTeX in AUC-TeX,
the FILE may also be composed of the following simple TeX commands.
  \`\\input{FILE}'     the actual file to compile
  \`\\nonstopmode\     same as --batch

Makeinfo is used to perform Texinfo macro expansion before running TeX
when needed.

Operation modes:
  -b, --batch         no interaction
  -D, --debug         turn on shell debugging (set -x)
  -h, --help          display this help and exit successfully
  -o, --output=OFILE  leave output in OFILE (implies --clean);
                      Only one input FILE may be specified in this case
  -q, --quiet         no output unless errors (implies --batch)
  -s, --silent        same as --quiet
  -v, --version       display version information and exit successfully
  -V, --verbose       report on what is done

TeX tuning:
  -@                   use @input instead of \input; for preloaded Texinfo
  -e, -E, --expand     force macro expansion using makeinfo
  -I DIR               search DIR for Texinfo files
  -l, --language=LANG  specify the LANG of FILE (LaTeX or Texinfo)
  -p, --pdf            use pdftex or pdflatex for processing
  -r, --recode         call recode before TeX to translate input characters
  -t, --command=CMD    insert CMD in copy of input file
   or --texinfo=CMD    multiple values accumulate

Build modes:
  --build=MODE         specify the treatment of auxiliary files [$build_mode]
      --tidy           same as --build=tidy
  -c, --clean          same as --build=clean
      --build-dir=DIR  specify where the tidy compilation is performed.
                       implies --tidy
                       defaults to TEXI2DVI_BUILD_DIRECTORY [$build_dir]

The MODE specifies where the TeX compilation takes place, and, as a
consequence, how auxiliary files are treated.  The build mode
can also be set using the environment variable TEXI2DVI_BUILD_MODE.

Valid MODEs are:
  \`local'      compile in the current directory, leaving all the auxiliary
                 files around.  This is the traditional TeX use.
  \`tidy'       compile in a local *.t2d directory, where the auxiliary files
                 are left.  Output files are copied back to the original file.
  \`clean'      same as \`tidy', but remove the auxiliary directory afterwards.
                 Every compilation therefore requires the full cycle.

Using the \`tidy' mode brings several advantages:
  - the current directory is not cluttered with plethora of temporary files.
  - clutter can be even reduced using --build-dir=dir: all the *.t2d
    directories are stored there.
  - clutter can be reduced to zero using --build-dir=/tmp/\$USER.t2d or
    --build-dir=$HOME/.t2d.
  - the output file is updated after every succesful TeX run, for
    sake of concurrent visualization of the output.  In a \`local' build
    the viewer stops during the whole TeX run.
  - if the compilation fails, the previous state of the output file
    is preserved.
  - PDF and DVI compilation are kept in separate subdirectories
    preventing any possibility of auxiliary file incompatibility.

On the other hand, because \`tidy' compilation takes place in another
directory, occasionally TeX won't be able to find some files (e.g., when
using \\graphicspath): in that case use -I to specify the additional
directories to consider.

The values of the BIBTEX, LATEX (or PDFLATEX), MAKEINDEX, MAKEINFO,
TEX (or PDFTEX), TEXINDEX, and THUMBPDF environment variables are used
to run those commands, if they are set.  Any CMD strings are added
after @setfilename for Texinfo input, in the first line for LaTeX input.

Email bug reports to <bug-texinfo@gnu.org>,
general questions and discussion to <help-texinfo@gnu.org>.
Texinfo home page: http://www.gnu.org/software/texinfo/"

# Initialize variables for option overriding and otherwise.
# Don't use `unset' since old bourne shells don't have this command.
# Instead, assign them an empty value.
line_error=true # Pass --file-line-error to TeX.
batch=false     # true for batch mode
debug=false
escape="\\"
expand=         # t for expansion via makeinfo
includes=
out_lang=dvi
oname=          # --output
quiet=false     # by default let the tools' message be displayed
recode=false
set_language=
textra=         # Extra TeX commands to insert in the input file.
txiprereq=19990129 # minimum texinfo.tex version with macro expansion
verb=false      # true for verbose mode

orig_pwd=`pwd`

# Systems which define $COMSPEC or $ComSpec use semicolons to separate
# directories in TEXINPUTS -- except for Cygwin, where COMSPEC might be
# inherited, but : is used.
if test -n "$COMSPEC$ComSpec" && uname | grep -iv cygwin >/dev/null; then
  path_sep=";"
else
  path_sep=":"
fi

# Pacify verbose cds.
CDPATH=${ZSH_VERSION+.}$path_sep

# In case someone crazy insists on using grep -E.
: ${EGREP=egrep}


## --------------------- ##
## Auxiliary functions.  ##
## --------------------- ##


# In case `local' is not supported by the shell.
(
  foo=bar
  test_local () {
    local foo=foo
  }
  test_local
  test $foo = bar
) || local () {
  case $1 in
    *=*) eval "$1";;
  esac
}


# func_dirname FILE
# -----------------
# Return the directory part of FILE.
func_dirname ()
{
  dirname "$1" 2>/dev/null \
  || { echo "$1" | sed 's!/[^/]*$!!;s!^$!.!'; }
}


# absolute NAME -> ABS-NAME
# -------------------------
# Return an absolute path to NAME.
absolute ()
{
  case $1 in
   [\\/]* | ?:[\\/]*)
      # Absolute paths don't need to be expanded.
      echo "$1"
      ;;
   *)
      (cd "$orig_pwd/`func_dirname $1`" 2>/dev/null &&
       echo `pwd`/`basename "$1"`)
      ;;
  esac
}


# findprog PROG
# -------------
# Return true if PROG is somewhere in PATH, else false.
findprog ()
{
  local saveIFS=$IFS
  IFS=$path_sep  # break path components at the path separator
  for dir in $PATH; do
    IFS=$saveIFS
    # The basic test for an executable is `test -f $f && test -x $f'.
    # (`test -x' is not enough, because it can also be true for directories.)
    # We have to try this both for $1 and $1.exe.
    #
    # Note: On Cygwin and DJGPP, `test -x' also looks for .exe.  On Cygwin,
    # also `test -f' has this enhancement, bot not on DJGPP.  (Both are
    # design decisions, so there is little chance to make them consistent.)
    # Thusly, it seems to be difficult to make use of these enhancements.
    #
    if  { test -f "$dir/$1"	&& test -x "$dir/$1"; } ||
	{ test -f "$dir/$1.exe"	&& test -x "$dir/$1.exe"; }; then
      return 0
    fi
  done
  return 1
}

# report LINE1 LINE2...
# ---------------------
# Report some information on stderr.
report ()
{
  for i in "$@"
  do
    echo >&2 "$0: $i"
  done
}

# Report some verbose information.
verbose ()
{
  $verb && echo >&2 "$0: $@"
}

# fatal EXIT_STATUS LINE1 LINE2...
# --------------------------------
# Report an error and exit with failure.
fatal ()
{
  s=$1
  shift
  report "$@"
  exit $s
}

# ensure_dir DIR1 DIR2...
# -----------------------
# Make sure the directories exist.
ensure_dir ()
{
  for dir
  do
    test -d "$dir" \
      || mkdir "$dir" \
      || fatal 1 "cannot create directory: $dir"
  done
}


## ---------------- ##
## Handling lists.  ##
## ---------------- ##


# list_append LIST ELEM
# ---------------------
list_append ()
{
  local la_l="$1"
  shift
  eval set X \$$la_l "$@"
  shift
  eval $la_l=\""$@"\"

  eval echo list_append: $la_l=\$$la_l
}

# list_prefix LIST SEP -> STRING
# ----------------------------
list_prefix ()
{
  local lp_p=$2
  eval set X \$$1
  shift
  local lp_res
  for i
  do
    lp_res="$lp_res \"$lp_p\" \"$i\""
  done
  echo "$lp_res"
}

# list_infix LIST SEP -> STRING
# ----------------------------
list_infix ()
{
  eval set X \$$1
  shift
  local la_IFS=$IFS
  IFS=$path_sep
  echo "$*"
  IFS=$la_IFS
}

# list_dir_to_abs LIST
# --------------------
# Convert the list to using only absolute dir names.
list_dir_to_abs ()
{
  local ld_l=$1
  eval set X \$$ld_l
  shift
  local ld_res
  for dir
  do
    dir=`absolute "$dir"`
    test -d "$dir" || continue
    ld_res="$ld_res \"$dir\""
  done
  echo "list_dir_to_abs: $ld_res"
  set X $ld_res; shift
  eval $ld_l=\"$@\"
  eval echo $ld_l=\$$ld_l
}

## ------------------------- ##
## TeX auxiliary functions.  ##
## ------------------------- ##

# Save TEXINPUTS so we can construct a new TEXINPUTS path for each file.
# Likewise for bibtex and makeindex.
tex_envvars="BIBINPUTS BSTINPUTS INDEXSTYLE TEXINPUTS"
for var in $tex_envvars; do
  eval ${var}_orig=\$$var
  export $var
done


# get_index_files FILE1 FILE2...
# ------------------------------
# Select the files that are indexes to run texindex/makeindex onto.
get_index_files ()
{
  for file
  do
    case `sed '1q' $file` in
      "\\entry{"*|"\\indexentry{"*) echo "$file";;
    esac
  done
}

# absolute_filenames TEX-PATH -> TEX-PATH
# ---------------------------------------
# Convert relative paths to absolute paths, so we can run in another
# directory (e.g., in tidy build mode, or during the macro-support
# detection).
#
# Empty path components are meaningful to tex.  We rewrite them
# as `EMPTY' so they don't get lost when we split on $path_sep.
# Hopefully no one will have an actual directory named EMPTY.
absolute_filenames ()
{
  local replace_empty="-e 's/^$path_sep/EMPTY$path_sep/g' \
                       -e 's/$path_sep\$/${path_sep}EMPTY/g' \
                       -e 's/$path_sep$path_sep/${path_sep}EMPTY:/g'"
  local res=`echo "$1" | eval sed $replace_empty`
  save_IFS=$IFS
  IFS=$path_sep
  set x $res; shift
  res=.
  for dir
  do
    case $dir in
      EMPTY)
        res=$res$path_sep
        ;;
      *)
        test -d $dir && res=$res$path_sep`absolute "$dir"`
        ;;
    esac
  done
  echo "$res"
}


# output_base_name FILE
# ---------------------
# The name of the FILE possibly renamed to satisfy --output.
output_base_name ()
{
  case $oname in
    '') echo "$1";;
     *) local out_noext=`echo "$oname" | sed 's/\.[^.]*$//'`
	local file_ext=`echo "$1" | sed 's/^.*\.//'`
	echo "$out_noext.$file_ext"
      ;;
  esac
}

# move_to_dest FILE
# -----------------
# Move the FILE to the place where the user expects it.  FILE can be
# the principal output (in which case -o directly apply), or an auxiliary
# file with the same base name.
move_to_dest ()
{
  local dest

  case $tidy:$oname in
    true:)  dest=$orig_pwd;;
    false:) dest=;;
    *:*)    dest=$(output_base_name "$1");;
  esac
  if test ! -f "$1"; then
    fatal 1 "no such file or directory: $1"
  fi
  if test -n "$dest"; then
    verbose "Copying $1 to $dest"
    cp -p "$1" "$dest"
  fi
}


## --------------------- ##
## Managing xref files.  ##
## --------------------- ##


# xref_files_get FILENAME-NOEXT
# -----------------------------
# Compute the list of xref files (indexes, tables and lists).
xref_files_get ()
{
  if $tidy; then
    # In a tidy build, all the files around as actual outputs.
    ls * 2>/dev/null
  else
    # Find all files having root filename with a two-letter extension,
    # saves the ones that are really Texinfo-related files.
    # - .?o?
    #   .toc, .log, LaTeX tables and lists, FiXme's .lox, maybe more.
    # - bu[0-9]*.aux
    #   Sub bibliography when using the LaTeX bibunits package.
    ls "$1".?o? "$1".aux bu[0-9]*.aux "$1".?? "$1".idx 2>/dev/null
  fi |
  while read file; do
    # If the file is not suitable to be an index or xref file, don't
    # process it.  It's suitable if the first character is a
    # backslash or right quote or at, as long as the first line isn't
    # \input texinfo.
    case `sed '1q' $file` in
      "\\input texinfo"*) ;;
      [\\''@]*) echo "./$file";;
    esac
  done
}

# xref_files_save
# ---------------
# Save the xref files.
xref_files_save ()
{
  # Save copies of auxiliary files for later comparison.
  xref_files_orig=`xref_files_get  "$in_noext"`
  if test -n "$xref_files_orig"; then
    verbose "Backing up xref files: $xref_files_orig"
    cp $xref_files_orig "$work_bak"
  fi
}


# xref_files_changed
# ------------------
# Whether the xref files were changed since the previous run.
xref_files_changed ()
{
  # LaTeX (and the package changebar) report in the LOG file if it
  # should be rerun.  This is needed for files included from
  # subdirs, since texi2dvi does not try to compare xref files in
  # subdirs.  Performing xref files test is still good since LaTeX
  # does not report changes in xref files.
  grep "Rerun to get" "$in_noext.log" >&6 2>&1 &&
    return 0

  # If old and new lists don't at least have the same file list,
  # then one file or another has definitely changed.
  xref_files_new=`xref_files_get  "$in_noext"`
  verbose "Original xref files = $xref_files_orig"
  verbose "New xref files      = $xref_files_new"
  test "x$xref_files_orig" != "x$xref_files_new" &&
    return 0

  # Compare each file until we find a difference.
  for this_file in $xref_files_new; do
    verbose "Comparing xref file `echo $this_file | sed 's|\./||g'` ..."
    # cmp -s returns nonzero exit status if files differ.
    if cmp -s "$this_file" "$work_bak/$this_file"; then :; else
      verbose "xref file `echo $this_file | sed 's|\./||g'` differed ..."
      $debug && diff -u "$work_bak/$this_file" "$this_file"
      return 0
    fi
  done

  # No change.
  return 1
}

## ----------------------- ##
## Running the TeX suite.  ##
## ----------------------- ##

# run_tex ()
# ----------
# Run TeX as "$tex $in_input", taking care of errors and logs.
run_tex ()
{
  case $language:$out_lang in
    latex:dvi)   tex=${LATEX:-latex};;
    latex:pdf)   tex=${PDFLATEX:-pdflatex};;
    texinfo:dvi)
        # MetaPost also uses the TEX environment variable.  If the user
        # has set TEX=latex for that reason, don't bomb out.
        case $TEX in
	  *latex) tex=tex;; # don't bother trying to find etex
	       *) tex=$TEX
        esac;;
    texinfo:pdf) tex=$PDFTEX;;

    *) fatal 1 "$out_lang not supported for $language";;
  esac

  # Beware of aux files in subdirectories that require the
  # subdirectory to exist.
  case $language:$tidy in
    latex:true)
       sed -n 's|^[ ]*\\include{\(.*\)/.*}.*|\1|p' $in_input |
       sort -u |
       while read d
       do
	 ensure_dir "$work_build/$d"
       done
       ;;
  esac

  # Note that this will be used via an eval: quote properly.
  local cmd=$tex

  # If possible, make TeX report error locations in GNU format.
  if test "${tex_help:+set}" != set; then
    # Go to a temporary directory to try --help, since old versions that
    # don't accept --help will generate a texput.log.
    tex_help_dir=$t2ddir/tex_help
    ensure_dir "$tex_help_dir"
    tex_help=`cd "$tex_help_dir" >&6 && $tex --help </dev/null 2>&1`
  fi
  $line_error && case $tex_help in
    *file-line-error*) cmd="$cmd --file-line-error";;
  esac

  # Tell TeX to be batch if requested.
  if $batch; then
    # \batchmode does not show terminal output at all, so we don't
    # want that.  And even in batch mode, TeX insists on having input
    # from the user.  Close its stdin to make it impossible.
    cmd="$cmd </dev/null '${escape}nonstopmode' '${escape}input'"
  fi

  # TeX's \input does not support white spaces in file names.  Our
  # intensive use of absolute file names makes this worse: the
  # enclosing directory names may include white spaces.  Improve the
  # situation using a symbolic link.  Do not alter in_input.
  case $tidy:`func_dirname "$in_input"` in
    true:*' '*)
      _run_tex_file_name=`basename "$in_input"`
      if test ! -f "$_run_tex_file_name"; then
	verbose ln -sf "$in_input"
        ln -sf "$_run_tex_file_name"
      fi
      cmd="$cmd '$_run_tex_file_name'"
      ;;

    *)
      cmd="$cmd '$in_input'"
      ;;
  esac

  verbose "Running $cmd ..."
  if eval "$cmd" >&5; then
    move_to_dest "$in_noext.$out_lang"
  else
    fatal 1 "$tex exited with bad status, quitting."
  fi
}

# run_bibtex ()
# -------------
# Run bibtex on current file.
# - If its input (AUX) exists.
# - If some citations are missing (LOG contains `Citation').
#   or the LOG complains of a missing .bbl
#
# We run bibtex first, because I can see reasons for the indexes
# to change after bibtex is run, but I see no reason for the
# converse.
#
# Don't try to be too smart:
#
# 1. Running bibtex only if the bbl file exists and is older than
# the LaTeX file is wrong, since the document might include files
# that have changed.
#
# 3. Because there can be several AUX (if there are \include's),
# but a single LOG, looking for missing citations in LOG is
# easier, though we take the risk to match false messages.
run_bibtex ()
{
  case $language in
    latex)   bibtex=${BIBTEX:-bibtex};;
    texinfo) return;;
  esac

  # "Citation undefined" is for LaTeX, "Undefined citation" for btxmac.tex.
  if test -r "$in_noext.aux" \
     && test -r "$in_noext.log" \
     && (grep 'Warning:.*Citation.*undefined' "$in_noext.log" \
          || grep '.*Undefined citation' "$in_noext.log" \
          || grep 'No file .*\.bbl\.' "$in_noext.log") \
        >&6 2>&1; \
  then
    # If using the bibunits package, we might have to run bibtex
    # on subfiles.
    for f in "$in_noext".aux bu[0-9]*.aux
    do
      if test -s "$f" && \
         (grep '^\\bibstyle[{]' "$f"   \
          && grep '^\\citation[{]' "$f"
	  ## The following line is suspicious: fails when there
	  ## are citations in sub aux files.  We need to be
	  ## smarter in this case.
          ## && grep '^\\bibdata[{]' "$f" \
	  ) >&6 2>&1; then
        verbose "Running $bibtex $f ..."
        $bibtex "$f" >&5 ||
          fatal 1 "$bibtex exited with bad status, quitting."
      fi
    done
  fi
}

# run_index ()
# ------------
# Run texindex (or makeindex) on current index files.  If they already
# exist, and after running TeX a first time the index files don't
# change, then there's no reason to run TeX again.  But we won't know
# that if the index files are out of date or nonexistent.
run_index ()
{
  case $language in
    latex)   texindex=${MAKEINDEX:-makeindex};;
    texinfo) texindex=${TEXINDEX:-texindex};;
  esac
  index_files=`get_index_files $xref_files_orig`
  if test -n "$texindex" && test -n "$index_files"; then
    verbose "Running $texindex $index_files ..."
    $texindex $index_files 2>&5 1>&2 ||
       fatal 1 "$texindex exited with bad status, quitting."
  fi
}


# run_thumbpdf ()
# ---------------
run_thumbpdf ()
{
  if test $out_lang = pdf \
     && test -r "$in_noext.log" \
     && grep 'thumbpdf\.sty'  "$in_noext.log" >&6 2>&1; \
  then
    thumbpdf=${THUMBPDF:-thumbpdf}
    verbose "Running $thumbpdf $in_noext ..."
    if $thumbpdf "$in_noext" >&5; then
      run_tex
    else
      report "$thumbpdf exited with bad status." \
	     "Ignoring its output."
    fi
  fi
}


# run_tex_suite ()
# ----------------
# Run the TeX tools until a fix point is reached.
run_tex_suite ()
{
  # Count the number of cycles.
  local cycle=0

  while :; do
    cycle=`expr $cycle + 1`
    verbose "Cycle $cycle for $command_line_filename"

    xref_files_save

    run_bibtex
    run_index
    run_tex

    xref_files_changed || break
  done

  # If we were using thumbpdf and producing PDF, then run thumbpdf
  # and TeX one last time.
  run_thumbpdf
}

## -------------------------------- ##
## TeX processing auxiliary tools.  ##
## -------------------------------- ##


# A sed script that preprocesses Texinfo sources in order to keep the
# iftex sections only.  We want to remove non TeX sections, and comment
# (with `@c texi2dvi') TeX sections so that makeinfo does not try to
# parse them.  Nevertheless, while commenting TeX sections, don't
# comment @macro/@end macro so that makeinfo does propagate them.
# Unfortunately makeinfo --iftex --no-ifinfo doesn't work well enough
# (yet), makeinfo can't parse the TeX commands, so work around with sed.
#
comment_iftex=\
'/^@tex/,/^@end tex/{
  s/^/@c texi2dvi/
}
/^@iftex/,/^@end iftex/{
  s/^/@c texi2dvi/
  /^@c texi2dvi@macro/,/^@c texi2dvi@end macro/{
    s/^@c texi2dvi//
  }
}
/^@ifnottex/,/^@end ifnottex/{
  s/^/@c (texi2dvi)/
}
/^@ifinfo/,/^@end ifinfo/{
  /^@node/p
  /^@menu/,/^@end menu/p
  t
  s/^/@c (texi2dvi)/
}
s/^@ifnotinfo/@c texi2dvi@ifnotinfo/
s/^@end ifnotinfo/@c texi2dvi@end ifnotinfo/'

# Uncommenting is simple: Remove any leading `@c texi2dvi'.
uncomment_iftex='s/^@c texi2dvi//'


# run_makeinfo ()
# ---------------
# Expand macro commands in the original source file using Makeinfo.
# Always use `end' footnote style, since the `separate' style
# generates different output (arguably this is a bug in -E).  Discard
# main info output, the user asked to run TeX, not makeinfo.
run_makeinfo ()
{
  case $language in
  texinfo)
    # Unless required by the user, makeinfo expansion is wanted only
    # if texinfo.tex is too old.
    if test "$expand" = t; then
      makeinfo=${MAKEINFO:-makeinfo}
    else
      # Check if texinfo.tex performs macro expansion by looking for
      # its version.  The version is a date of the form YEAR-MO-DA.
      # We don't need to use [0-9] to match the digits since anyway
      # the comparison with $txiprereq, a number, will fail with non
      # digits.
      # Run in a temporary directory to avoid leaving files.
      version_test_dir=$t2ddir/version_test
      ensure_dir "$version_test_dir"
      (
         cd "$version_test_dir"
         echo '\input texinfo.tex @bye' >txiversion.tex
         # Be sure that if tex wants to fail, it is not interactive:
         # close stdin.
         tex txiversion.tex </dev/null >txiversion.out 2>txiversion.err
      )
      if test $? != 0; then
        cat $version_test_dir/txiversion.out
        cat $version_test_dir/txiversion.err >&2
        fatal 1 "texinfo.tex appears to be broken, quitting."
      fi
      eval `sed -n 's/^.*\[\(.*\)version \(....\)-\(..\)-\(..\).*$/txiformat=\1 txiversion="\2\3\4"/p' $version_test_dir/txiversion.out`
      verbose "texinfo.tex preloaded as \`$txiformat', version is \`$txiversion' ..."
      if test "$txiprereq" -le "$txiversion" >&6 2>&1; then
        makeinfo=
      else
        makeinfo=${MAKEINFO:-makeinfo}
      fi
      # As long as we had to run TeX, offer the user this convenience:
      test "$txiformat" = Texinfo && escape=@
    fi

    if test -n "$makeinfo"; then
      # in_src: the file with macros expanded.
      # Use the same basename to generate the same aux file names.
      work_src=$workdir/src
      ensure_dir "$work_src"
      in_src=$work_src/$in_base
      local $miincludes=`list_prefix includes -I`
      verbose "Macro-expanding $command_line_filename to $in_src ..."
      sed "$comment_iftex" "$command_line_filename" \
        | $makeinfo --footnote-style=end -I "$in_dir" $miincludes \
          -o /dev/null --macro-expand=- \
        | sed "$uncomment_iftex" >"$in_src"
      # Continue only if everything succeeded.
      if test $? -ne 0 \
         || test ! -r "$in_src"; then
        verbose "Expansion failed, ignored...";
      else
        in_input=$in_src
      fi
    fi
    ;;
  esac
}

# insert_commands ()
# ------------------
# Used most commonly for @finalout, @smallbook, etc.
insert_commands ()
{
  local textra_cmd
  case $language in
    latex)   textra_cmd=1i;;
    texinfo) textra_cmd='/^@setfilename/a';;
    *)       echo "$0: internal error, unknown language: $language" >&2;
  esac

  if test -n "$textra"; then
    # _xtr.  The file with the user's extra commands.
    work_xtr=$workdir/xtr
    in_xtr=$work_xtr/$in_base
    ensure_dir "$work_xtr"
    verbose "Inserting extra commands: $textra"
    sed "$textra_cmd\\
$textra" "$in_input" >"$in_xtr"
    in_input=$in_xtr
  fi
}

# run_recode ()
# -------------
# If this is a Texinfo file with a specified input encoding, and
# recode is available, then recode to plain 7 bit Texinfo.
run_recode ()
{
  if test $language = texinfo; then
    pgm='s/^ *@documentencoding  *\([^ ][^ ]*\) *$/\1/
	t found
	d
	:found
	q'
    encoding=`sed -e "$pgm" "$in_input"`
    if $recode && test -n "$encoding" && findprog recode; then
      verbose "Recoding from $encoding to Texinfo."
      # _rcd.  The Texinfo file recoded in 7bit.
      work_rcd=$workdir/recode
      in_rcd=$work_rcd/$in_base
      ensure_dir "$work_rcd"
      if recode "$encoding"..texinfo <"$in_input" >"$in_rcd" \
         && test -s "$in_rcd"; then
        in_input=$in_rcd
      else
        verbose "Recoding failed, using original input."
      fi
    fi
  fi
}

# compute_language FILENAME
# -------------------------
# Return the short string describing the language in which FILENAME
# is written: `texinfo' or `latex'.
compute_language ()
{
  # If the user explicitly specified the language, use that.
  # Otherwise, if the first line is \input texinfo, assume it's texinfo.
  # Otherwise, guess from the file extension.
  if test -n "$set_language"; then
    echo $set_language
  elif sed 1q "$1" | grep 'input texinfo' >&6; then
    echo texinfo
  else
    # Get the type of the file (latex or texinfo) from the given language
    # we just guessed, or from the file extension if not set yet.
    case $1 in
      *.ltx | *.tex | *.drv | *.dtx) echo latex;;
      *)                             echo texinfo;;
    esac
  fi
}


# run_to_html ()
# --------------
# Convert to HTML.
run_to_html ()
{
  hevea=${HEVEA:-hevea}

  # Compiling to the tmp directory enables to preserve a previous
  # successful compilation.  Unfortunately it makes it hard to move
  # the image back to the destination directory.  So compile to the
  # actual destination.
  local to_html="$hevea -fix -noiso -O -o '$out_name'"
  to_html="$to_html `list_prefix includes -I`"
  to_html="$to_html '$in_input'"

  verbose "running $to_html"
  if eval "$to_html" >&5; then :; else
    fatal 1 "$hevea exited with bad status, quitting."
  fi
}


# run_conversion ()
# -----------------
# Run the TeX tools until a fix point is reached.
run_conversion ()
{
  # Move to the working directory.
  if $tidy; then
    verbose "cd $work_build"
    cd "$work_build" || exit 1
  fi

  case $out_lang in
    dvi|pdf) run_tex_suite;;
    html   ) run_to_html;;
  esac

  # In case $orig_pwd is on a different drive (for DOS).
  cd /

  # Return to the original directory so that
  # - the next file is processed in correct conditions
  # - the temporary file can be removed
  cd "$orig_pwd" || exit 1
}

## ---------------------- ##
## Command line parsing.  ##
## ---------------------- ##

# Push a token among the arguments that will be used to notice when we
# ended options/arguments parsing.
# Use "set dummy ...; shift" rather than 'set - ..." because on
# Solaris set - turns off set -x (but keeps set -e).
# Use ${1+"$@"} rather than "$@" because Digital Unix and Ultrix 4.3
# still expand "$@" to a single argument (the empty string) rather
# than nothing at all.
arg_sep="$$--$$"
set dummy ${1+"$@"} "$arg_sep"; shift

# 
# Parse command line arguments.
while test x"$1" != x"$arg_sep"; do

  # Handle --option=value by splitting apart and putting back on argv.
  case "$1" in
    --*=*)
      opt=`echo "$1" | sed -e 's/=.*//'`
      val=`echo "$1" | sed -e 's/[^=]*=//'`
      shift
      set dummy "$opt" "$val" ${1+"$@"}; shift
      ;;
  esac

  # This recognizes --quark as --quiet.  So what.
  case "$1" in
    -@ ) escape=@;;
    # Silently and without documentation accept -b and --b[atch] as synonyms.
    -b | --batch) batch=true;;
         --build)      shift; build_mode=$1;;
         --build-dir)  shift; build_dir=$1; build_mode=tidy;;
    -c | --clean) build_mode=clean;;
    -D | --debug) debug=true;;
    -e | -E | --expand) expand=t;;
    -h | --help) echo "$usage"; exit 0;;
         --html) out_lang=html;;
    -I | --I*)
      shift
      list_append includes "$1"
      ;;
    -l | --lang | --language) shift; set_language=$1;;
    -o | --out  | --output)
      shift
      # Make it absolute, just in case we also have --clean, or whatever.
      oname=`absolute "$1"`;;
    -p | --pdf) out_lang=pdf;;
    -q | -s | --quiet | --silent) quiet=true; batch=true;;
    -r | --recode) recode=true;;
    -t | --texinfo | --command ) shift; textra="$textra\\
"`echo "$1" | sed 's/\\\\/\\\\\\\\/g'`;;
    --tidy) build_mode=tidy;;
    -v | --vers*) echo "$version"; exit 0;;
    -V | --verb*) verb=true;;
    --) # What remains are not options.
      shift
      while test x"$1" != x"$arg_sep"; do
        set dummy ${1+"$@"} "$1"; shift
        shift
      done
      break;;
    -*)
      fatal 1 "Unknown or ambiguous option \`$1'." \
              "Try \`--help' for more information."
      ;;
    *) set dummy ${1+"$@"} "$1"; shift;;
   esac
   shift
done
# Pop the token
shift

# $tidy:  compile in a t2d directory.
# $clean: remove the t2d directory afterward.
case $build_mode in
  local) clean=true;  tidy=false;;
  tidy)  clean=false; tidy=true;;
  clean) clean=true;  tidy=true;;
      *) fatal 1 "invalid build mode: $build_mode";;
esac

# Interpret remaining command line args as filenames.
case $# in
 0)
  fatal 2 "Missing file arguments." "Try \`--help' for more information."
  ;;
 1) ;;
 *)
  if test -n "$oname"; then
    fatal 2 "Can't use option \`--output' with more than one argument."
  fi
  ;;
esac


# Use absolute dir names in the includes.
list_dir_to_abs includes


# We can't do much without tex.
#
if findprog ${TEX:-tex}; then :; else cat <<EOM
You don't have a working TeX binary (${TEX:-tex}) installed anywhere in
your PATH, and texi2dvi cannot proceed without one.  If you want to use
this script, you'll need to install TeX (if you don't have it) or change
your PATH or TEX environment variable (if you do).  See the --help
output for more details.

For information about obtaining TeX, please see http://www.tug.org.  If
you happen to be using Debian, you can get it with this command:
  apt-get install tetex-bin
EOM
  exit 1
fi


# We want to use etex (or pdftex) if they are available, and the user
# didn't explicitly specify.  We don't check for elatex and pdfelatex
# because (as of 2003), the LaTeX team has asked that new distributions
# use etex by default anyway.
#
# End up with the TEX and PDFTEX variables set to what we are going to use.
if test -z "$TEX"; then
  if findprog etex; then TEX=etex; else TEX=tex; fi
fi
#
if test -z "$PDFTEX"; then
  if findprog pdfetex; then PDFTEX=pdfetex; else PDFTEX=pdftex; fi
fi


# File descriptor usage:
# 0 standard input
# 1 standard output (--verbose messages)
# 2 standard error
# 3 some systems may open it to /dev/tty
# 4 used on the Kubota Titan
# 5 tools output (turned off by --quiet)
# 6 tracing/debugging (set -x output, etc.)


# Main tools' output (TeX, etc.) that TeX users are used to seeing.
#
# If quiet, discard, else redirect to the message flow.
if $quiet; then
  exec 5>/dev/null
else
  exec 5>&1
fi


# Enable tracing, and auxiliary tools output.
#
# Should be used where you'd typically use /dev/null to throw output
# away.  But sometimes it is convenient to see that output (e.g., from
# a grep) to aid debugging.  Especially debugging at distance, via the
# user.
if $debug; then
  exec 6>&1
  set -x
else
  exec 6>/dev/null
fi

# 

# input_file_name_decode
# ----------------------
# Decode COMMAND_LINE_FILENAME, and compute:
# - COMMAND_LINE_FILENAME clean of TeX commands
# - IN_DIR
#   The directory to the input file, possibly absolute if needed.
# - IN_DIR_ABS
#   The absolute directory of the input file.
# - IN_BASE
#   The input file base name (no directory part).
# - IN_NOEXT
#   The input file name without extensions (nor directory part).
# - IN_INPUT
#   Defaults to COMMAND_LINE_FILENAME, but might change if the
#   input is preprocessed (recode etc.).  With directory, possibly absolute.
input_file_name_decode ()
{
  # See if we are run from within AUC-Tex, in which case we are
  # passed `\input{FOO.tex}' or even `\nonstopmode\input{FOO.tex}'.
  case $command_line_filename in
    *\\nonstopmode*)
      batch=true;;
  esac
  case $command_line_filename in
    *\\input{*}*)
      # Let AUC-TeX error parser deal with line numbers.
      line_error=false
      command_line_filename=`\
        expr X"$command_line_filename" : X'.*input{\([^}]*\)}'`
      ;;
  esac

  # If the COMMAND_LINE_FILENAME is not absolute (e.g., --debug.tex),
  # prepend `./' in order to avoid that the tools take it as an option.
  echo "$command_line_filename" | $EGREP '^(/|[A-z]:/)' >&6 \
  || command_line_filename="./$command_line_filename"

  # See if the file exists.  If it doesn't we're in trouble since, even
  # though the user may be able to reenter a valid filename at the tex
  # prompt (assuming they're attending the terminal), this script won't
  # be able to find the right xref files and so forth.
  test  -r "$command_line_filename" ||
    fatal 1 "cannot read $command_line_filename, skipping."

  # Get the name of the current directory.
  in_dir=`func_dirname "$command_line_filename"`
  in_dir_abs=`absolute "$in_dir"`
  # In a clean build, we `cd', so get an absolute file name.
  $tidy && in_dir=$in_dir_abs

  # Strip directory part but leave extension.
  in_base=`basename "$command_line_filename"`
  # Strip extension.
  in_noext=`echo "$in_base" | sed 's/\.[^.]*$//'`

  # The normalized file name to compile.  Must always point to the
  # file to actually compile (in case of recoding, macro-expansion etc.).
  in_input=$in_dir/$in_base


  # Compute the output file name.
  if test x"$oname" != x; then
    out_name=$oname
  else
    out_name=$in_noext.$out_lang
  fi
  out_dir=`func_dirname "$out_name"`
  out_dir_abs=`absolute "$out_dir"`
  out_base=`basename "$out_name"`
  out_noext=`echo "$out_base" | sed 's/\.[^.]*$//'`
}


## -------------- ##
## TeXify files.  ##
## -------------- ##

for command_line_filename in ${1+"$@"}; do
  verbose "Processing $command_line_filename ..."

  input_file_name_decode

  # An auxiliary directory used for all the auxiliary tasks involved
  # in compiling this document.
  case $build_dir in
      '' | . ) t2ddir=$out_noext.t2d ;;
      *) # Avoid collisions between multiple occurrences of the same
	 # file.
	 t2ddir=$build_dir/`echo "$out_dir_abs/$out_noext.t2d" | sed 's,/,!,g'`
  esac
  # Remove it at exit if clean mode.
  $clean &&
    trap "cd / && rm -rf $t2ddir" 0 1 2 15

  ensure_dir "$build_dir" "$t2ddir"

  # We will change directory, better work with an absolute path...
  t2ddir=`absolute "$t2ddir"`
  # Sometimes there are incompatibilities between auxiliary files for
  # DVI and PDF.  The contents can also change whether we work on PDF
  # and/or DVI.  So keep separate spaces for each.
  workdir=$t2ddir/$out_lang
  ensure_dir "$workdir"

  # _build.  In a tidy build, where the auxiliary files are output.
  if $tidy; then
    work_build=$workdir/build
  else
    work_build=.
  fi

  # _bak.  Copies of the previous auxiliary files (another round is
  # run if they differ from the new ones).
  work_bak=$workdir/bak

  # Make those directories.
  ensure_dir "$work_build" "$work_bak"

  # Source file might include additional sources.
  # We want `.:$orig_pwd' before anything else.  (We'll add `.:' later
  # after all other directories have been turned into absolute paths.)
  # `.' goes first to ensure that any old .aux, .cps,
  # etc. files in ${directory} don't get used in preference to fresher
  # files in `.'.  Include orig_pwd in case we are in clean build mode, where
  # we've cd'd to a temp directory.
  txincludes=`list_infix includes $path_sep`
  common="$orig_pwd$path_sep$in_dir$path_sep$txincludes$path_sep"
  for var in $tex_envvars; do
    eval val="\$common\$${var}_orig"
    # Convert relative paths to absolute paths, so we can run in another
    # directory (e.g., in clean build mode, or during the macro-support
    # detection).
    val=`absolute_filenames "$val"`
    eval $var="$val"
    eval export $var
    eval verbose "$var=\'\$${var}\'"
  done

  # `texinfo' or `latex'?
  language=`compute_language $command_line_filename`

  # --expand
  run_makeinfo

  # --command, --texinfo
  insert_commands

  # --recode
  run_recode

  # Run until a fix point is reached.
  run_conversion

  # Remove temporary files.
  if $clean; then
    verbose "Removing $t2ddir"
    rm -rf "$t2ddir"
  fi
done

verbose "done."
exit 0 # exit successfully, not however we ended the loop.
